package utils;

import org.h2.jdbc.JdbcSQLSyntaxErrorException;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class H2Utils {

    /**
     * H2 database driver full classname
     */
    public static final String H2_DRIVER = "org.h2.Driver";

    /**
     * H2 JDBC connection URL, embedded (local) connection
     */
    public static final String H2_JDBC_URL = "jdbc:h2:~/tmp/h2/exp6;AUTO_SERVER=TRUE";

    /**
     * A connection (session) with a specific database
     */
    private static Connection connection;

    static {
        try {
            /* H2 database initialize */
            final Connection conn = getConnection();
            final File SQL = FileUtils.getClasspathFile("scheme.sql");
            try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(SQL))) {
                conn.createStatement().execute(new String(in.readAllBytes(), StandardCharsets.UTF_8));
            }
        } catch (JdbcSQLSyntaxErrorException ignore) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Get a database connection (session) with a specific database
     *
     * @return a connection (session)
     */
    public static Connection getConnection() {
        try {
            if (connection == null || connection.isClosed()) {
                Class.forName(H2_DRIVER);
                connection = DriverManager.getConnection(H2_JDBC_URL);
            }

            return connection;
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        // Failed to get database connection
        throw new RuntimeException("Failed to get database connection");
    }

}
